﻿using System.Windows;
using System.Windows.Input;
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
//using Gma.UserActivityMonitor;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media.Imaging;

using System.Windows.Media.Animation;
//using WindowsInput;
using System.Threading;
using System.Windows.Threading;

using System.Windows.Media;
using SStuff.FlowControls;
using System.Windows.Documents;


namespace MercuryFE
{
    public partial class Simple : MyWindow
    {
        #region properties
        ProcessHandler _processHandler = null;
        
        private MenuLevel _currentMenu = null;
        private Dictionary<int, int> _levelSelection;
        private Dictionary<int, bool> _levelUnlocked;
        private ObservableCollection<MenuLink> _currentLinks = null;
        

 
        private static string _processErrorMessage = "";
        private static string _trackInfo = "";

        private bool _confirmedExit = false;

        private readonly int _fastMenuIncrement = 3;
        private bool _messageShown = false;
        private bool _popupMenuShown = false;
        private bool _gameDetailsShown = false;
        private bool _showBackgroundImage = true;
        //private bool _isVerticalNavigation = true;
        private bool _hasVerticalNavigation = true;
        private bool _hasHorizontalNavigation = true;
        private bool _passwordShown = false;

        private object selectionObject = null;

        

        #endregion

        #region delegates
        public delegate void ShowErrorMessageDelegate();
        private ShowErrorMessageDelegate showError;

        public delegate void ShowTrackInfoDelegate();
        private ShowTrackInfoDelegate showTrackinfo;

        public delegate void UpdateGameDetailsDelegate();
        private UpdateGameDetailsDelegate updateGameDetails;
        #endregion


        public Simple()
        {
            InitializeComponent();

           
            // set up for fullscreen if required
            string winStyle = ClientLib.getConfig("Window Style");
            if (winStyle == "fullscreen")
            {
                this.WindowState= System.Windows.WindowState.Maximized;
                this.WindowStyle= System.Windows.WindowStyle.None;
                this.AllowsTransparency = true;
                this.Background = Brushes.Transparent;
                this.Topmost = true;
            }


            _levelSelection = new Dictionary<int, int>();
            _levelUnlocked = new Dictionary<int, bool>();

            showError = new ShowErrorMessageDelegate(ShowErrorMessage);
            showTrackinfo = new ShowTrackInfoDelegate(ShowTrackInfo);
            updateGameDetails = new UpdateGameDetailsDelegate(updateCurrentGameDetails);

            _processHandler = new ProcessHandler(this);
            _processHandler.ProcessComplete += new ProcessHandler.ProcessCompletedHandler(_processHandler_ProcessComplete);

            //App.__navigationHook.CurrentNavigationType = NavigationHook.NavigationType.Standard;
            this.Loaded += new RoutedEventHandler(Simple_Loaded);

            // initialise different interface types
            string interfaceType = ClientLib.getConfig("Interface Type");
            if (interfaceType == "coverflow")
            {
                selectionObject = flow;
                flow.Visibility = System.Windows.Visibility.Visible;
                _showBackgroundImage = false;
                //_isVerticalNavigation = false;
                _hasHorizontalNavigation = true;
                _hasVerticalNavigation = false;
                vbMenuItemName.Visibility = System.Windows.Visibility.Visible;

                _currentLinks = new ObservableCollection<MenuLink>();
                flow.ItemsSource = _currentLinks;

            }
            //else
            //{
            //    selectionObject = lbMenu;
            //    lbMenu.Visibility = System.Windows.Visibility.Visible;
            //    _showBackgroundImage = true;
            //    _isVerticalNavigation = true;
            //}
            else
            {
                // listview
                selectionObject = lvMenu;
                lvMenu.Visibility = System.Windows.Visibility.Visible;
                _showBackgroundImage = false;

                _hasHorizontalNavigation = true;
                _hasVerticalNavigation = true;
            }



            getMenuLevel(0);

            //App.__soundHandler = new SoundHandler(meMusicPlayer);
            //App.__soundHandler.StartingNextTrack += new SoundHandler.StartingNextTrackHandler(__soundHandler_StartingNextTrack);
            //App.__soundHandler.loadTracksFromDBQueue();
        }





        void Simple_Loaded(object sender, RoutedEventArgs e)
        {
            // set up the input handling...
            App.InitialiseNavigation(_hasVerticalNavigation, _hasHorizontalNavigation, this); // true, since simple menu is up/down
        }
    
        public override void DoNavigation(NavigationHook.NavigationTask navigationTask, bool normalSpeed)
        {
            if (_popupMenuShown)
            {
                DoPopupMenuNavigation(navigationTask);
                return;
            }

            if (_gameDetailsShown)
            {
                DoGameDetailsNavigation(navigationTask);
                return;
            }

            if (_passwordShown)
            {
                DoPasswordNavigation(navigationTask);
            }

            int increment = 1;

            if (!normalSpeed)
                increment = _fastMenuIncrement;

            int maxIndex = _currentMenu.Links.Count - 1;
            int minIndex = 0;
            bool indexChange = false;

            int selectedIndex = getSelectedIndex(selectionObject);
           


            // clear the message on any key pressed (other than back)
            if (_messageShown &&((_confirmedExit && navigationTask != NavigationHook.NavigationTask.Back) || !_confirmedExit))
            {
                _messageShown = false;
                _confirmedExit = false;

                if ( messageGrid.Visibility != System.Windows.Visibility.Hidden)
                {
                    messageGrid.Visibility = System.Windows.Visibility.Hidden;
                }
                return;
            }

            switch (navigationTask)
            {
                case NavigationHook.NavigationTask.Left:
                    if (_hasHorizontalNavigation)
                    {
                        if (selectedIndex > minIndex)
                        {
                            if (selectedIndex > minIndex + increment)
                                setSelectedIndex(selectionObject, selectedIndex - increment);
                            //((Selector)lbMenu).SelectedIndex -= increment;
                            else
                                setSelectedIndex(selectionObject, selectedIndex - 1);
                            //((Selector)lbMenu).SelectedIndex--;
                        }
                        else
                            setSelectedIndex(selectionObject, maxIndex);

                        indexChange = true;
                    }

                    break;
                case NavigationHook.NavigationTask.Right:
                    if (_hasHorizontalNavigation)
                    {
                        if (selectedIndex == maxIndex)
                            setSelectedIndex(selectionObject, minIndex);
                        //((Selector)lbMenu).SelectedIndex = minIndex;
                        else
                        {
                            if (selectedIndex < maxIndex - increment)
                                setSelectedIndex(selectionObject, selectedIndex + increment);
                            //((Selector)lbMenu).SelectedIndex += increment;
                            else
                                setSelectedIndex(selectionObject, selectedIndex + 1);
                            //((Selector)lbMenu).SelectedIndex++;

                        }

                        indexChange = true;
                    }

                    break;
                case NavigationHook.NavigationTask.Up:

                    // if it has both directions (listview), we should try moving up/down the screen so to speak
                    if (_hasHorizontalNavigation && _hasVerticalNavigation)
                    {
                        // value defined for num items per row
                        int listViewItemsPerRow = (int)this.FindResource("ListViewItemsPerRow");

                        if (selectedIndex - listViewItemsPerRow >= 0)
                            setSelectedIndex(selectionObject, selectedIndex - listViewItemsPerRow);

                    }

                    else if (_hasVerticalNavigation)
                    {
                        if (selectedIndex > minIndex)
                        {
                            if (selectedIndex > minIndex + increment)
                                setSelectedIndex(selectionObject, selectedIndex - increment);
                            //((Selector)lbMenu).SelectedIndex -= increment;
                            else
                                setSelectedIndex(selectionObject, selectedIndex - 1);
                            //((Selector)lbMenu).SelectedIndex--;
                        }
                        else
                            setSelectedIndex(selectionObject, maxIndex);

                        indexChange = true;
                    }
                    break;
                case NavigationHook.NavigationTask.Down:
                    // if it has both directions (listview), we should try moving up/down the screen so to speak
                    if (_hasHorizontalNavigation && _hasVerticalNavigation)
                    {
                        // value defined for num items per row
                        int listViewItemsPerRow = (int)this.FindResource("ListViewItemsPerRow");

                        if (selectedIndex + listViewItemsPerRow <= maxIndex)
                            setSelectedIndex(selectionObject, selectedIndex + listViewItemsPerRow);

                    }
                    else if (_hasVerticalNavigation)
                    {
                        if (selectedIndex == maxIndex)
                            setSelectedIndex(selectionObject, minIndex);
                        //((Selector)lbMenu).SelectedIndex = minIndex;
                        else
                        {
                            if (selectedIndex < maxIndex - increment)
                                setSelectedIndex(selectionObject, selectedIndex + increment);
                            //((Selector)lbMenu).SelectedIndex += increment;
                            else
                                setSelectedIndex(selectionObject, selectedIndex + 1);
                            //((Selector)lbMenu).SelectedIndex++;

                        }

                        indexChange = true;
                    }
                    break;
                case NavigationHook.NavigationTask.Select:
                    this.handleLink();
                    break;
                case NavigationHook.NavigationTask.Back:
                    if (_currentMenu.Level != 0) //_currentLevel != 0)
                        getMenuLevel(_currentMenu.ParentMenuId);
                    else if (_confirmedExit == false)
                    {
                        showExitConfirmation();
                        _confirmedExit = true;
                    }
                    else
                    {
                        exitProgram();
                    }

                    break;
                case NavigationHook.NavigationTask.Pause:

                    this.showGameDetails();
                    break;

            }

            //// reset the exit confirmation, in case they changed their mind
            //if (navigationTask != NavigationHook.NavigationTask.Back)
            //    _confirmedExit = false;


            if (indexChange)
            {
                lbMenu_IndexUpdated();
            }
        }

        private int getSelectedIndex(object menu)
        {


            if (menu.GetType() == typeof(ListBox))
                return ((ListBox)menu).SelectedIndex;
            if (menu.GetType() == typeof(ListView))
                return ((ListView)menu).SelectedIndex;
            //else if (menu.GetType() == typeof(ElementFlow))
            //    return ((ElementFlow)menu).SelectedIndex;
            else if (menu.GetType() == typeof(FlowItemsControl3D))
                return ((FlowItemsControl3D)menu).SelectedIndex;
            else
                return -1;
        }

        private void setSelectedIndex(object menu, int value)
        {
            if (menu.GetType() == typeof(ListBox))
               ((ListBox)menu).SelectedIndex = value;
            else if (menu.GetType() == typeof(ListView))
                ((ListView)menu).SelectedIndex = value;
            else if (menu.GetType() == typeof(FlowItemsControl3D))
                ((FlowItemsControl3D)menu).SelectedIndex = value;

        }

        private void setItemSource(object menu, List<MenuLink> value, int? selectedIndex)
        {
            if (menu.GetType() == typeof(ListBox))
                ((ListBox)menu).ItemsSource = value;
            else if (menu.GetType() == typeof(ListView))
            {
                ((ListView)menu).ItemsSource = value;
                if(selectedIndex!=null)
                    ((ListView)menu).SelectedIndex = (int)selectedIndex;
            }
            //else if (menu.GetType() == typeof(ElementFlow))
            //{
            //    //((ElementFlow)menu).SelectedItem = null;
            //    ((ElementFlow)menu).SelectedIndex = -1;


            //    _currentLinks.Clear();
            //    foreach (MenuLink link in value)
            //    {
            //        _currentLinks.Add(link);
            //    }

            //    //((ElementFlow)menu).SelectedValue = null;
            //    //((ElementFlow)menu).ItemsSource = null;
            //   // ((ElementFlow)menu).ItemsSource = value;

            //}
            else if (menu.GetType() == typeof(FlowItemsControl3D))
            {
                //((ElementFlow)menu).SelectedItem = null;
                // ((FlowItemsControl3D)menu).SelectedIndex = -1;  // setting this to -1, then clearing was causing big issues...


                _currentLinks.Clear();
                int currentIndex = -1;
                foreach (MenuLink link in value)
                {
                    _currentLinks.Add(link);
                    currentIndex++;

                    // select the item as soon as we load it - save having to 'flick' around...
                    if (selectedIndex != null && currentIndex == selectedIndex)
                        ((FlowItemsControl3D)menu).SelectedIndex = (int)selectedIndex;
                }

                //((ElementFlow)menu).SelectedValue = null;
                //((ElementFlow)menu).ItemsSource = null;
                // ((ElementFlow)menu).ItemsSource = value;

            }
               // ((FlowItemsControl3D)menu).ItemsSource = value;
        }
  
        public void getMenuLevel(int menuId) 
        {

            _currentMenu = ClientLib.getMenuLevel(menuId, true);

            // find the right index to select (since we remember last time we visited the level)
            int selectedIndex = 0;
            if (_levelSelection.ContainsKey(_currentMenu.Level)) 
            {
                int prevSelection = _levelSelection[_currentMenu.Level]; 
                // check if key in links
                for (int i = 0; i < _currentMenu.Links.Count; i++)
                {
                    MenuLink link = _currentMenu.Links[i];
                    if (link.Key == prevSelection && link.IsMenu)
                    {
                        selectedIndex = i;
                        break;
                    }
                }
            }

            setItemSource(selectionObject, _currentMenu.Links, selectedIndex);
            //setSelectedIndex(selectionObject, selectedIndex);
            lbMenu_IndexUpdated();
        }

        void lbMenu_IndexUpdated()
        {
            // called when a new selection is made - updates all the text/ icons on the interface nicely..
            string textValue = "";
            string menuPath = "";

            bool bShowPlayStats = false;
            bool bShowNumPlayers = false;

            spNPlayers.Children.Clear();
            spEmulatorImage.Children.Clear();


            // if we have links for this menu path - try and get the value..
            int currentIndex = getSelectedIndex(selectionObject);

            if (_currentMenu.Links.Count > 0 && currentIndex >= 0)
            {

                // scroll into view
                if (selectionObject.GetType() == typeof(ListBox))
                    ((ListBox)selectionObject).ScrollIntoView(((Selector)selectionObject).SelectedItem);
             
                if (currentIndex < _currentMenu.Links.Count)
                {
                    MenuLink currentItem = _currentMenu.Links[currentIndex];


                   // check if game has an image...
                    if (currentItem.HasImage && _showBackgroundImage && File.Exists(currentItem.Image))
                    {
                        var uriSource = new Uri(currentItem.Image, UriKind.Absolute);
                        BackgroundImage.Source = new BitmapImage(uriSource);

                        //BackgroundImage.Visibility = System.Windows.Visibility.Visible;
                        backgroundImageGrid.Visibility = System.Windows.Visibility.Visible;
 

                    }
                    else
                    {
                        //BackgroundImage.Visibility = System.Windows.Visibility.Hidden;
                        backgroundImageGrid.Visibility = System.Windows.Visibility.Hidden;
                    }


                    // text along bottom (title)
                    textValue = currentItem.Name.ToString();
                    if (currentItem.IsMenu)
                    {
                        //textValue = "[ " + textValue + " ]";
                    }
                    else
                    {
                        // a game...
                        if (currentItem.IsGame)
                        {

                            // played stats
                            bShowPlayStats = true;
                            tbLastPlayed.Text = currentItem.LastPlayed == null ? "Never" : ((DateTime)currentItem.LastPlayed).ToLongDateString();
                            tbNumberPlayed.Text = currentItem.NumberTimesPlayed == null ? "Never" : currentItem.NumberTimesPlayed.ToString();
                            tbTotalPlayed.Text = currentItem.TotalTimePlayed == null ? "Never" : currentItem.TotalTimePlayed.ToString() + " mins";


                            // always show emulator image (or attempt anyway)
                            if(currentItem.EmulatorImage!=null && File.Exists(currentItem.EmulatorImage))
                                spEmulatorImage.Children.Add(ClientLib.getImage(currentItem.EmulatorImage));


                            // other stuff is mame specific
                            if (currentItem.IsMame)
                            {
                                spNPlayers.Children.Add(ClientLib.generateNPlayersImage(currentItem.NPlayers));
                                bShowNumPlayers = true;

                            }
                        }
                        else
                        {
                            // music
                        }

                    }
                    //if(tbMenuItemName.IsVisible)
                        tbMenuItemName.Text = textValue;


                }

            }

            menuPath = string.Join(" - ", _currentMenu.MenuPath.ToArray());

            //tbTitle.Text = textValue;
            tbPathCrumb.Text = menuPath;


            ClientLib.showHideElement(bShowPlayStats, bPlayStats);
            ClientLib.showHideElement(bShowNumPlayers, gNumPlayers);

        }

        public void launchGame(int gameId)
        {
            string error = "";
            string commandline = "";

            //App.__navigationHook.setGameKeyMappings(gameId);

            bool success = _processHandler.LaunchGame(gameId, ref error, ref commandline);

            if (!success)
            {
                _processErrorMessage = _processHandler.ErrorMessage;
                showError();
            }

            if (!App.__soundHandler.IsPlaying)
                App.__soundHandler.resume();

        }

        private void showExitConfirmation()
        {
            showMessage("Are you sure you want to leave?" + Environment.NewLine + Environment.NewLine  + "Press 'Back' again to confirm.");
        }

        private void hideMessage()
        {
            messageGrid.Visibility = System.Windows.Visibility.Hidden;
            //message.Visibility = System.Windows.Visibility.Hidden;
            //messageBackground.Visibility = System.Windows.Visibility.Hidden;
            _messageShown = false;
        }

        private void showMessage(string messageString)
        {
            messageGrid.Visibility = System.Windows.Visibility.Visible;
            message.Text = messageString;
            //message.Visibility = System.Windows.Visibility.Visible;
            //messageBackground.Visibility = System.Windows.Visibility.Visible;
            _messageShown = true;
        }

        private void exitProgram()
        {
            // initiate exit sequence
            ClientLib.exitProgram();
        }

        private void handleLink()
        {
            int index = getSelectedIndex(selectionObject); // ((Selector)lbMenu).SelectedIndex;

            MenuLink link = _currentMenu.Links[index];

            if (link.IsMenu)
            {
                /*
                // check if level is password protected, and hasn't been unlocked
                if (link.SecuredLevel && !_levelUnlocked.ContainsKey(link.Key))
                {
                    // display message.. need to check for password
                    showPopupPassword();
                }
                else
                {
                 * */

                    if (_levelSelection.ContainsKey(_currentMenu.Level))
                        _levelSelection[_currentMenu.Level] = link.Key;
                    else
                        _levelSelection.Add(_currentMenu.Level, link.Key);

                    getMenuLevel(link.Key);
                /*}*/
            }
            else if (link.IsGame)
            {
                launchGame(link.Key);
            }
            else
            {
                // music - will launch a new window for the tracks that are part of the collection... 
                // this interface will provide some way of adding
                /*
                PopupMenu popupMenu = new PopupMenu(link.Key)
                {
                    Width = this.ActualWidth / 2
                    ,
                    Height = this.ActualHeight / 2
                    ,
                    Owner = this
                    ,
                    ShowActivated = true
                };


                popupMenu.Show();
                 * */
                showPopupMenu(link.Key);
                
            }

        }



        // event handlers
        void gd_Closed(object sender, EventArgs e)
        {
            App.InitialiseNavigation(_hasHorizontalNavigation, _hasHorizontalNavigation, this);
        }

        void _processHandler_ProcessComplete(string ErrorMessage)
        {
            if (ErrorMessage != "")
            {
                _processErrorMessage = ErrorMessage;

                this.Dispatcher.Invoke(DispatcherPriority.Normal, showError);
            }
            else
            {
                this.Dispatcher.Invoke(DispatcherPriority.Normal, updateGameDetails);
            }


        }

        void __soundHandler_StartingNextTrack(int trackId)
        {
            // populate and display the music 'popup'... will need a storyboard or something?

            string title = "";
            string artist = "";
            ClientLib.getTrackInfo(trackId, ref artist, ref title);
            _trackInfo =  title + Environment.NewLine + artist;

            this.Dispatcher.Invoke(DispatcherPriority.Normal, showTrackinfo);
 
        }

        // delegates
        public void ShowTrackInfo()
        {
            tbTrackInfo.Text = _trackInfo;

            Storyboard sb = (Storyboard)this.FindResource("fadeIn");
            sb.Begin();
        }


        public void ShowErrorMessage()
        {
            showMessage(_processErrorMessage);
        }

        public void ResumeMusic()
        {
            App.__soundHandler.resume();
        }

        /// <summary>
        /// call this to update information on the current game after being launched/ closed (ie, # of times played, total play time, etc)
        /// </summary>
        private void updateCurrentGameDetails()
        {
            if (_currentMenu.Links.Count > 0 && getSelectedIndex(selectionObject) >= 0) //((Selector)lbMenu).SelectedIndex
            {
                int currentIndex = getSelectedIndex(selectionObject); // ((Selector)lbMenu).SelectedIndex;
                if (currentIndex < _currentMenu.Links.Count)
                {
                    MenuLink updatedItem = ClientLib.getGameMenuLink(_currentMenu.Links[currentIndex].Key);
                    _currentMenu.Links[currentIndex] = updatedItem;
                }
            }
            lbMenu_IndexUpdated();
        }

        public override void PauseMame()
        {
            this.IsMamePaused = true;
            showGameDetails();

        }


        #region popupMenu

        private int _popupMenuSourceKey;

        public void showPopupMenu(int sourceKey)
        {
            _popupMenuSourceKey = sourceKey;
            popupMenuGrid.Visibility = System.Windows.Visibility.Visible;
            _popupMenuShown = true;
            populateMenu();
        }


        

        private void populateMenu()
        {
            popupMenu.Items.Clear();
            popupMenu.Items.Add("Add to end of queue");
            popupMenu.Items.Add("Add to top of queue");
            popupMenu.Items.Add("Replace queue");

            popupMenu.SelectedIndex = 0;
        }

        private void handlePopupMenuSelect()
        {
            string selection = (string)popupMenu.SelectedItem;

            if (selection == "Add to end of queue")
            {
                App.__soundHandler.addCollectionToQueue(_popupMenuSourceKey, SoundHandler.AddToQueueType.Bottom);
            }
            else if (selection == "Add to top of queue")
            {
                App.__soundHandler.addCollectionToQueue(_popupMenuSourceKey, SoundHandler.AddToQueueType.Top);
            }
            else
            {
                App.__soundHandler.addCollectionToQueue(_popupMenuSourceKey, SoundHandler.AddToQueueType.Replace);
            }

            //this.Close();
            _popupMenuShown = false;
            popupMenuGrid.Visibility = System.Windows.Visibility.Hidden;
        }

        public void DoPopupMenuNavigation(NavigationHook.NavigationTask navigationTask)
        {

            int maxIndex = popupMenu.Items.Count - 1;
            int minIndex = 0;

            switch (navigationTask)
            {
                case NavigationHook.NavigationTask.Left:

                    break;
                case NavigationHook.NavigationTask.Right:

                    break;
                case NavigationHook.NavigationTask.Up:

                    if (popupMenu.SelectedIndex > minIndex)
                        popupMenu.SelectedIndex--;
                    else
                        popupMenu.SelectedIndex = maxIndex;
                    break;
                case NavigationHook.NavigationTask.Down:
                    if (popupMenu.SelectedIndex == maxIndex)
                        popupMenu.SelectedIndex = minIndex;
                    else
                        popupMenu.SelectedIndex++;
                    break;
                case NavigationHook.NavigationTask.Select:
                    handlePopupMenuSelect();
                    break;
                case NavigationHook.NavigationTask.Back:

                    popupMenuGrid.Visibility = System.Windows.Visibility.Hidden;
                    _popupMenuShown = false;
                    break;
                case NavigationHook.NavigationTask.Pause:
                    break;

            }

        }


        public void showPopupPassword()
        {
            pbPassword.Password = "";
            passwordGrid.Visibility = System.Windows.Visibility.Visible;
            _passwordShown = true;
        }

        public void DoPasswordNavigation(NavigationHook.NavigationTask navigationTask)
        {

            switch (navigationTask)
            {
                case NavigationHook.NavigationTask.Select:
                    handlePopupMenuSelect();
                    break;
                case NavigationHook.NavigationTask.Back:

                    popupMenuGrid.Visibility = System.Windows.Visibility.Hidden;
                    _popupMenuShown = false;
                    break;
            }

        }
        #endregion


        #region gameDetails

        private void showGameDetails()
        {
            int index = getSelectedIndex(selectionObject);

            MenuLink link = _currentMenu.Links[index];

            if (!link.IsMenu)
            {

                _gameDetailsShown = true;
                gameDetailsGrid.Visibility = System.Windows.Visibility.Visible;

                ClientLib.generateDetails(link.Key, ref Viewer, ref tbName, this);


            }

        }

        private void hideGameDetails()
        {

            _gameDetailsShown = false;
            gameDetailsGrid.Visibility = System.Windows.Visibility.Hidden;
            Viewer.ItemsSource = null;
            tbName.Text = "";
        }


        public void DoGameDetailsNavigation(NavigationHook.NavigationTask navigationTask)
        {
            bool changeDocument = false;
            bool scrollDocument = false;
            bool scrollDown = true;



            switch (navigationTask)
            {
                case NavigationHook.NavigationTask.Left:
                    if (Viewer.SelectedIndex != 0)
                    {
                        Viewer.ScrollIntoView(Viewer.Items[--Viewer.SelectedIndex]);
                        changeDocument = true;
                    }
                    break;
                case NavigationHook.NavigationTask.Right:
                    if (Viewer.SelectedIndex != Viewer.Items.Count - 1)
                    {
                        Viewer.ScrollIntoView(Viewer.Items[++Viewer.SelectedIndex]);
                        changeDocument = true;
                    }
                    break;
                case NavigationHook.NavigationTask.Up:
                    scrollDocument = true;
                    scrollDown = false;
                    break;
                case NavigationHook.NavigationTask.Down:
                    scrollDocument = true;
                    break;
                case NavigationHook.NavigationTask.Select:

                    break;
                case NavigationHook.NavigationTask.Back:
                    hideGameDetails();
                    if (this.IsMamePaused)
                    {
                        this.IsMamePaused = false;
                        _processHandler.MameUnpaused();
                    }
                    
                    break;
                case NavigationHook.NavigationTask.Pause:

                    break;

            }

            if (changeDocument)
            {
                FlowDocument item = (FlowDocument)Viewer.SelectedItem;
                item.Focus();
            }

            if (scrollDocument)
            {
                FlowDocument doc = (FlowDocument)Viewer.SelectedItem;
                FlowDocumentPageViewer docViewer = (FlowDocumentPageViewer)doc.Parent;
                if (scrollDown)
                {
                    if (docViewer.CanGoToNextPage)
                    {
                        docViewer.NextPage();
                    }
                }
                else
                {
                    if (docViewer.CanGoToPreviousPage)
                    {
                        docViewer.PreviousPage();
                    }
                }
            }

        }
        #endregion


        private bool validatePassword()
        {
            int index = getSelectedIndex(selectionObject); // ((Selector)lbMenu).SelectedIndex;

            MenuLink link = _currentMenu.Links[index];
            if(link.IsMenu) {

                string password = pbPassword.Password.ToString();
                int menuId = link.Key;

                if (ClientLib.validatePassword(menuId, password))
                {
                    _levelUnlocked.Add(menuId,true);
                    return true;
                }
            }
            return false;
        }
    }
}
